package com.attendancesystem.service;

import com.attendancesystem.model.Unit;
import com.attendancesystem.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UnitService {
    public List<Unit> getUnitList(){
        String sql="select * from units";
        List<Unit> unitList=new ArrayList<>();
        try(Connection conn= JDBCUtils.getConnection();
            PreparedStatement pstmt=conn.prepareStatement(sql)){
            ResultSet rs=pstmt.executeQuery();
            while (rs.next()){
                Unit unit=new Unit();
                unit.setUnitId(rs.getInt("unit_id"));
                unit.setUnitName(rs.getString("unit_name"));
                unit.setUnitDescription(rs.getString("unit_description"));
                unit.setCourseId(rs.getInt("course_id"));
                unit.setUnitDuration(rs.getInt("unit_duration"));
                unitList.add(unit);
            }

        }catch (SQLException e){
            e.printStackTrace();
        }
        return unitList;
    }
    public Boolean addUnit(Unit unit){
        String sql="insert into units(unit_name,unit_description,course_id,unit_duration) values(?,?,?,?)";
        try(Connection conn=JDBCUtils.getConnection();
            PreparedStatement pstmt=conn.prepareStatement(sql)){
            pstmt.setString(1,unit.getUnitName());
            pstmt.setString(2,unit.getUnitDescription());
            pstmt.setInt(3,unit.getCourseId());
            pstmt.setInt(4,unit.getUnitDuration());
            if(pstmt.executeUpdate()>0){
                return true;
            }
            }catch (SQLException e){
            e.printStackTrace();
        }
        return false;
    }
    public Boolean deleteUnit(int unitId){
        String sql="delete from units where unit_id=?";
        try(Connection conn=JDBCUtils.getConnection();
            PreparedStatement pstmt=conn.prepareStatement(sql)){
            pstmt.setInt(1,unitId);
            if(pstmt.executeUpdate()>0){
                return true;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return false;
   }
    public Boolean updateUnit(Unit unit){
        String sql="update units set unit_name=?,unit_description=?,course_id=?,unit_duration=? where unit_id=?";
        try(Connection conn=JDBCUtils.getConnection();
            PreparedStatement pstmt=conn.prepareStatement(sql)){
            pstmt.setString(1,unit.getUnitName());
            pstmt.setString(2,unit.getUnitDescription());
            pstmt.setInt(3,unit.getCourseId());
            pstmt.setInt(4,unit.getUnitDuration());
            pstmt.setInt(5,unit.getUnitId());
            if(pstmt.executeUpdate()>0){
                return true;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return false;
    }
}
